vlwkaos' digital garden

Rust - functions

  • 반환을 안하는 함수는 빈 tuple을 반환함

declaration

fn hello() {
  //...
}

with arguments

fn printNums(num: i32) {
    for i in 0..num {
        println!("Number {}", i + 1);
    }
}

with return type

1

fn sale_price(price: i32) -> i32 {
    if is_even(price) {
        price - 10
    } else {
        price - 3
    }
}

2

fn is_even(num: i32) -> bool {
    num % 2 == 0
}
  • 뒤에 ;이 붙으면 statement
  • 없으면 expression. Expression은 반환된다.

Referred in

[Rust - functions](https://doc.rust-lang.org/book/ch03-03-how-functions-work.html)